<?php
/*
 * @component AlphaUserPoints
 * @copyright Copyright (C) 2008-2010 Bernard Gilly
 * @license : GNU/GPL
 * @Website : http://www.alphaplug.com
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

class alphauserpointsModelcurrentrequests extends Jmodel {

	function __construct(){
		parent::__construct();
		
	}
	
	function _getCurrentRequests ( $userid, $usergid ) {
	
		$db	=& JFactory::getDBO();
		
		$usergidNextLevel = $usergid + 1;
		//$usergidPreviousLevel = $usergid - 1;
		 
		$query = "SELECT * FROM #__alpha_userpoints_requests WHERE userid='$userid' AND checked='0' AND response='0' AND levelrequest='$usergidNextLevel'";
		$db->setQuery( $query );
		$result = $db->loadObjectList();		
		
		return $result;
	
	}
	
	function _setNewRequest() {
	
		$app = JFactory::getApplication();
	
		$jnow		=& JFactory::getDate();
		$now		= $jnow->toMySQL();
		
		$user = & JFactory::getUser();
		
		$referrerid = @$_SESSION['referrerid'];
		
		JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_alphauserpoints'.DS.'tables');		
		// save new request into alpha_userpoints_requests table
		$row =& JTable::getInstance('userspointsrequests');
		$row->id				= NULL;		
		$row->userid			= $user->id;		
		$row->referreid			= $referrerid;		
		$row->name				= $user->name;
		$row->username			= $user->username;
		$row->levelrequest		= $user->gid + 1;
		$row->checked			= 0;
		$row->checkedadmin		= 0;
		$row->response			= 0;
		$row->requestdate 		= $now;
		
		if ( !$row->store() ) 
		{
			JError::raiseError(500, $row->getError());
		}
		
		$db	   =& JFactory::getDBO();
		$mailfrom	= $app->getCfg('mailfrom'); 	
		$fromname	= $app->getCfg('fromname'); 				
		$subject 	= JText::_( 'AUP_REQUEST_CHANGE_LEVEL' );
		$message 	= "";
		
		//get all super administrator
		$query = "SELECT name, email, sendEmail" .
				" FROM #__users" .
				" WHERE LOWER( usertype )='super administrator'";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();

		// get superadministrators id
		foreach ( $rows as $row )
		{
			if ($row->sendEmail)
			{
				$message = sprintf ( JText::_( 'AUP_SEND_MSG_ADMIN_REQUEST_CHANGE_LEVEL' ), $row->name, $user->name, $user->username);
				$message = html_entity_decode($message, ENT_QUOTES);
				JUtility::sendMail($mailfrom, $fromname, $row->email, $subject, $message);
			}
		}

	}	

}
?>